// import { useToast } from '@/utils/modals'
import store from '@/store/index.js'

const homePath = '/pages/index/home/index'
const loginPath = '/pages/login/account/index'
const registerPath = '/pages/register/account/index'

const whiteList = [loginPath, registerPath, '/pages/statement/index', '/pages/webview/index']

function permission(router) {
  const userStore = store.useUserStore()

  const loginRoute = to => ({
    path: loginPath,
    navType: 'reLaunch',
    force: true,
    query: {
      redirect: JSON.stringify({
        path: to.path,
        query: to.query,
      }),
    },
  })

  router.beforeEach((to, from, next) => {
    const token = userStore.token
    if (token) {
      if (to.path === loginPath) {
        next(homePath)
      }
      else {
        next()
      }
    }
    else if (whiteList.includes(to.path)) {
      next()
    }
    else {
      next(loginRoute(to))
    }
  })
}

export default permission
